import 'dart:math';

import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/commission.dart';
import 'package:boss/ui/page/commission/commission_page.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class CommissionProvider extends ChangeNotifier {
  Map<String, List<Commission>> data = {
    Commission.BEGINNING: [],
    Commission.UN_BEGIN: [],
    Commission.END: [],
  };

  Future<Result<List<Commission>>> queryCommissions(String status) async {
    try {
      var res = await api.queryCommissionList(status);
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      data[status] = res.data;
      notifyListeners();

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  addCommission(Commission commission) async {
    if (!RegUtil.testNotEqEmpty(commission.commissionName)) {
      toast('提成名称不能为空');
      return;
    }

    if (commission.commissionAmount == null) {
      toast('提成金额不能为空');
      return;
    }

    try {
      showLoadingToast();

      if (!commission.isFixed) {
        commission.commissionAmount = min(commission.commissionAmount, 10000);
      }

      var res = await api.addCommission(commission);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }
      toast('保存成功');

      queryCommissions(commission.status);

      Navigator.popUntil(GlobalPageContext.instance.context, ModalRoute.withName(CommissionPage.pageName));
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  Future endCommission(Commission commission) async {
    try {
      showLoadingToast();

      var res = await api.deleteCommission(commission.id);

      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      data[commission.status].removeWhere((item) => item.id == commission.id);
      data[Commission.END].add(commission);
      notifyListeners();

      toast('操作成功');

      Navigator.popUntil(GlobalPageContext.instance.context, ModalRoute.withName(CommissionPage.pageName));
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }
}
